package cn.ainit.yz.printexplain;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;


import oracle.jdbc.OracleTypes;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.butn.proceduce.ButScripParams;
import cn.ainit.butn.proceduce.CommonProcedure;
import cn.ainit.common.ReturnObject;
import cn.ainit.sys.common.dao.BusinessBaseDao;
import cn.ainit.yz.execut.entity.Execut;
import cn.ainit.yz.execut.entity.ExecutFM;
import cn.ainit.yz.execut.entity.ExecutZD;
import cn.ainit.yz.execut.entity.ExecutZW;
import cn.ainit.yz.printexplain.entity.PrintExplainFM;
import cn.ainit.yz.printexplain.entity.PrintExplainZD;
import cn.ainit.yz.printexplain.entity.PrintExplainZW;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.utils.UUID32;
import cn.ainit.yz.printexplain.entity.PrintExplain;
import cn.ainit.yz.printexplain.entity.PrintExplainFM;

@Transactional
@Repository("printExplainDao")
public class PrintExplainDaoImpl extends BusinessBaseDao implements PrintExplainDao{
	@Override
	public String printToexec(String peId) throws Exception {
		String putValue="";
		Connection conn = null;
		CallableStatement cs = null;
		try {
			 conn= this.getJdbcTemplate().getDataSource().getConnection();
			 String sql = "{Call PK_YZ.up_YssmToSgd(?,?)}";
			 cs = conn.prepareCall(sql);
			 cs.setString(1,peId);
			 cs.registerOutParameter(2,oracle.jdbc.OracleTypes.VARCHAR);
			 cs.execute();
			 putValue = cs.getString(2);
		} catch (Exception e) {
			e.getMessage();
			throw e;
		}finally{
			if (cs != null) {
				cs.close();
			}
			if(conn != null){
				conn.close();
			}
		}
		return putValue;
	}
	@Override
	public String caiLiaoChuku(String peId) throws Exception {
		String putValue="";
		Connection conn = null;
		CallableStatement cs = null;
		try {
			 conn= this.getJdbcTemplate().getDataSource().getConnection();
			 String sql = "{Call PK_YZ.up_YssmToClCK(?,?)}";
			 cs = conn.prepareCall(sql);
			 cs.setString(1,peId);
			 cs.registerOutParameter(2,oracle.jdbc.OracleTypes.VARCHAR);
			 cs.execute();
			 putValue = cs.getString(2);
		} catch (Exception e) {
			e.getMessage();
			throw e;
		}finally{
			if (cs != null) {
				cs.close();
			}
			if(conn != null){
				conn.close();
			}
		}
		return putValue;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<PrintExplainFM> findFMList(String ysId) throws Exception {
		try {
			String hql = "from PrintExplainFM pr where pr.peId ='"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<PrintExplainFM> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PrintExplainZD> findZDList(String ysId) throws Exception {
		try {
			String hql = "from PrintExplainZD zd where zd.peId = '"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<PrintExplainZD> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PrintExplainZW> findZWList(String ysId) throws Exception {
		try {
			String hql = "from PrintExplainZW zw where zw.peId = '"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<PrintExplainZW> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public boolean saveBase(PrintExplain printExplain) throws Exception {
		this.getSessionFactory().getCurrentSession().save(printExplain);
		return true;
	}
	
	@Override
	public boolean updateBase(PrintExplain printExplain) throws Exception {
		this.getSessionFactory().getCurrentSession().update(printExplain);
		return true;
	}
	
	@Override
	public List saveFM(List<PrintExplainFM> printExplainFMs,String peId)
			throws Exception {
		List<String> idsList = new ArrayList<String>();
		if (peId == null || peId.equals("")) {
			throw new RuntimeException("请先保存印刷说明单基本信息");
		}
		List<PrintExplainFM> oldList = new ArrayList<PrintExplainFM>();
		List<PrintExplainFM> newList = new ArrayList<PrintExplainFM>();
		//需要删除的封面印刷ID
		StringBuffer peFMIds = new StringBuffer("");
		//遍历明细 判断相应条件
		for (int i = 0; i < printExplainFMs.size(); i++) {
			if (printExplainFMs.get(i).getPeFengmianId() != null && (!printExplainFMs.get(i).getPeFengmianId().equals(""))) {
				//说明是原有的封面印刷
				idsList.add(printExplainFMs.get(i).getPeFengmianId());
				printExplainFMs.get(i).setPeId(peId);
				oldList.add(printExplainFMs.get(i));
				peFMIds.append("'"+printExplainFMs.get(i).getPeFengmianId()+"',");
			}else{
				//新添加的封面印刷
				idsList.add(UUID32.newGuid());
				printExplainFMs.get(i).setPeId(peId);
				printExplainFMs.get(i).setPeFengmianId(idsList.get(i));
				newList.add(printExplainFMs.get(i));
			}
		}
		//删除废弃的封面印刷
		String ids = peFMIds.toString();
		if (!ids.equals("")) {
			ids = ids.substring(0, peFMIds.toString().length()-1);
			String sql = " delete from yz_print_explain_fm pefm where pefm.pe_id = '"+peId+"' ";
			sql += " and pefm.pe_fengmian_id not in ("+ids+") ";
			this.getJdbcTemplate().execute(sql);
		}
		//保存数据
		for (int i = 0; i < oldList.size(); i++) {
			this.getSessionFactory().getCurrentSession().update(oldList.get(i));
		}
		//更新数据
		for (int i = 0; i < newList.size(); i++) {
			this.getSessionFactory().getCurrentSession().save(newList.get(i));
		}
		return idsList;
	}
	/***
	 * 保存正文印刷
	 */
	@Override
	public List saveZW(List<PrintExplainZW> printExplainZWs,String peId)
			throws Exception {
		List<String> idsList = new ArrayList<String>();
		if (peId == null || peId.equals("")) {
			throw new RuntimeException("请先保存印刷说明单基本信息");
		}
		List<PrintExplainZW> oldList = new ArrayList<PrintExplainZW>();
		List<PrintExplainZW> newList = new ArrayList<PrintExplainZW>();
		//需要删除的封面印刷ID
		StringBuffer peFMIds = new StringBuffer("");
		//遍历明细 判断相应条件
		for (int i = 0; i < printExplainZWs.size(); i++) {
			if (printExplainZWs.get(i).getPeFengmianId() != null && (!printExplainZWs.get(i).getPeFengmianId().equals(""))) {
				//说明是原有的封面印刷
				idsList.add(printExplainZWs.get(i).getPeFengmianId());
				printExplainZWs.get(i).setPeId(peId);
				oldList.add(printExplainZWs.get(i));
				peFMIds.append("'"+printExplainZWs.get(i).getPeFengmianId()+"',");
			}else{
				//新添加的封面印刷
				idsList.add(UUID32.newGuid());
				printExplainZWs.get(i).setPeId(peId);
				printExplainZWs.get(i).setPeFengmianId(idsList.get(i));
				newList.add(printExplainZWs.get(i));
			}
		}
		//删除废弃的封面印刷
		String ids = peFMIds.toString();
		if (!ids.equals("")) {
			ids = ids.substring(0, peFMIds.toString().length()-1);
			String sql = " delete from yz_print_explain_zw pefm where pefm.pe_id = '"+peId+"' ";
			sql += " and pefm.pe_fengmian_id not in ("+ids+") ";
			this.getJdbcTemplate().execute(sql);
		}
		//保存数据
		for (int i = 0; i < oldList.size(); i++) {
			this.getSessionFactory().getCurrentSession().update(oldList.get(i));
		}
		//更新数据
		for (int i = 0; i < newList.size(); i++) {
			this.getSessionFactory().getCurrentSession().save(newList.get(i));
		}
		return idsList;
	}
	
	@Override
	public List saveZD(List<PrintExplainZD> printExplainZDs,String peId)
			throws Exception {
		List<String> idsList = new ArrayList<String>();
		if (peId == null || peId.equals("")) {
			throw new RuntimeException("请先保存印刷说明单基本信息");
		}
		List<PrintExplainZD> oldList = new ArrayList<PrintExplainZD>();
		List<PrintExplainZD> newList = new ArrayList<PrintExplainZD>();
		//需要删除的封面印刷ID
		StringBuffer peFMIds = new StringBuffer("");
		//遍历明细 判断相应条件
		for (int i = 0; i < printExplainZDs.size(); i++) {
			if (printExplainZDs.get(i).getPeFengmianId() != null && (!printExplainZDs.get(i).getPeFengmianId().equals(""))) {
				//说明是原有的封面印刷
				idsList.add(printExplainZDs.get(i).getPeFengmianId());
				printExplainZDs.get(i).setPeId(peId);
				oldList.add(printExplainZDs.get(i));
				peFMIds.append("'"+printExplainZDs.get(i).getPeFengmianId()+"',");
			}else{
				//新添加的封面印刷
				idsList.add(UUID32.newGuid());
				printExplainZDs.get(i).setPeId(peId);
				printExplainZDs.get(i).setPeFengmianId(idsList.get(i));
				newList.add(printExplainZDs.get(i));
			}
		}
		//删除废弃的封面印刷
		String ids = peFMIds.toString();
		if (!ids.equals("")) {
			ids = ids.substring(0, peFMIds.toString().length()-1);
			String sql = " delete from yz_print_explain_zd pefm where pefm.pe_id = '"+peId+"' ";
			sql += " and pefm.pe_fengmian_id not in ("+ids+") ";
			this.getJdbcTemplate().execute(sql);
		}
		//保存数据
		for (int i = 0; i < oldList.size(); i++) {
			this.getSessionFactory().getCurrentSession().update(oldList.get(i));
		}
		//更新数据
		for (int i = 0; i < newList.size(); i++) {
			this.getSessionFactory().getCurrentSession().save(newList.get(i));
		}
		return idsList;
	}
	@Override
	public Execut getOneExecut(String exId) throws Exception {
		return (Execut) this.getSessionFactory().getCurrentSession().get(Execut.class, exId);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<ExecutFM> findExFMList(String ysId) throws Exception {
		try {
			String hql = "from ExecutFM pr where pr.exId ='"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<ExecutFM> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExecutZD> findExZDList(String ysId) throws Exception {
		try {
			String hql = "from ExecutZD zd where zd.exId = '"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<ExecutZD> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExecutZW> findExZWList(String ysId) throws Exception {
		try {
			String hql = "from ExecutZW zw where zw.exId = '"+ysId+"'";
			Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
			List<ExecutZW> listZds = query.list();
			if (listZds !=null) {
				return listZds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 印刷付印单添加批次的时
	 * @param xtId
	 * @param byc
	 * @param config
	 * @return
	 * @throws Exception
	 * @author feifei
	 * @date: 2015-3-30 上午11:41:22 
	 */
	@Override
	public String returnNewBath(String xtId, String byc, String config)
			throws Exception {
		String sql="SELECT t.pici  FROM (SELECT pe.pici FROM yz_print_explain pe  WHERE pe.xt_id =? AND pe.banyinci = ? AND pe.is_destroy = '0' ORDER BY nvl(pe.pici, 0) DESC) t  WHERE ROWNUM = 1";
		String  data = jdbcTemplate.queryForObject(sql,String.class,new Object[]{xtId,byc});  
		return data;
	}
	
	@Override
	public String keepModifyPrems(String dsId,String djId,HttpSession session)
			throws Exception {
		Connection conn=null;
		CallableStatement cs=null;
		String isMP=null;
		try {
			String sql="{Call PK_MODIFY_PERMS.UP_KEEP_MODIFY_YP(?,?,?,?)}";
			conn=this.jdbcTemplate.getDataSource().getConnection();
			cs=conn.prepareCall(sql);
			cs.setString(1, djId);
			cs.setString(2, dsId);
			cs.setString(3, (String)session.getAttribute(SessionCont.uid));
			cs.registerOutParameter(4, Types.VARCHAR);
			cs.execute();
			isMP=cs.getString(4);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(cs!=null){
				cs.close();
			}
			if(conn!=null){
				conn.close();
			}
		}
		return isMP;
	}
}
